package com.kedsoft.andaily.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kedsoft.andaily.entity.*;
import com.kedsoft.andaily.mapper.BoardroomMapper;
import com.kedsoft.andaily.mapper.CunsumerMapper;
import com.kedsoft.andaily.mapper.NormalMapper;
import com.kedsoft.andaily.mapper.TaskMapper;
import com.kedsoft.andaily.service.NormalService;
import com.kedsoft.andaily.service.ParamService;
import com.kedsoft.andaily.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 生成日常任务
 */
@Service
public class NormalServiceImpl extends ServiceImpl<NormalMapper, Normal> implements NormalService {
    @Autowired
    NormalMapper normalMapper;

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    BoardroomMapper boardroomMapper;

    @Autowired
    CunsumerMapper cunsumerMapper;

    @Autowired
    ParamService paramService;
    /**
     * 获取所有没有被禁用的配电房
     * @return
     */
    private List<Boardroom> getBoardrooms(){
        EntityWrapper<Boardroom> wrapper = new EntityWrapper<>();
        wrapper.eq("status",1);
        List<Boardroom> list = boardroomMapper.selectList(wrapper);
        return list;
    }

    /**
     * 创建任务
     */
    public void createTask(){
        List<Boardroom> list = getBoardrooms();
        for (Boardroom bean:list) {
            try {
                //获取定时检查日期 50
                Date checktime = bean.getChecktime();
                //红外测温日期60
                Date hwcwtime = bean.getHwcwtime();
                //开关核对70
                Date kghdtime = bean.getKghdtime();
                //设备清扫40
                Date sbqstime = bean.getSbqstime();
                //环境清扫80
                Date hjqstime = bean.getHjqstime();
                Date tgtime = bean.getStoptime();
                if (checktime != null && tgtime!=null) {
                    //50
                    List<TaskType> listdsxj = getListDate(checktime, tgtime, "50");
                    addTask(listdsxj, bean);
                }
                if (hwcwtime != null && tgtime!=null) {
                    //60
                    List<TaskType> listhwcw = getListDate(hwcwtime, tgtime, "60");
                    addTask(listhwcw, bean);
                }
                if (kghdtime != null && tgtime!=null) {
                    //70
                    List<TaskType> listkghd = getListDate(kghdtime, tgtime, "70");
                    addTask(listkghd, bean);
                }
                if (sbqstime != null && tgtime!=null) {
                    //40
                    List<TaskType> listsbqs = getListDate(sbqstime, tgtime, "40");
                    addTask(listsbqs, bean);
                }
                if (hjqstime != null && tgtime!=null) {
                    //80
                    List<TaskType> listhjqs = getListDate(hjqstime, tgtime, "80");
                    addTask(listhjqs, bean);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void addTask(List<TaskType> listckDate,Boardroom bean){
        for(TaskType taskType: listckDate){
            Date starttime = taskType.getTime();
            Normal task = new Normal();
            //如果存在任务跳过
            EntityWrapper<Normal> normalEntityWrapper = new EntityWrapper<>();
            normalEntityWrapper.eq("boardid",bean.getId());
            normalEntityWrapper.eq("createtime",DateUtil.format(starttime));
            //normalEntityWrapper.eq("starttime",DateUtil.format(starttime));
            normalEntityWrapper.eq("tasktype",taskType.getType());
            List<Normal> listNormal = normalMapper.selectList(normalEntityWrapper);
            if(listNormal==null || listNormal.size()<=0) {
                //50代表日常巡视
                task.setTasktype(Integer.parseInt(taskType.getType()));
                task.setBoardname(bean.getBoardname());
                task.setBoardid(bean.getId());
                task.setBoardlat(bean.getBoardlat());
                task.setBoardlng(bean.getBoardlng());
                task.setCreatetime(starttime);
                task.setProjectid(bean.getProjectid());
                task.setProjectname(bean.getProjectname());
                task.setProjectcode(bean.getProjectcode());
                task.setVoltmark(bean.getVoltmark());
                task.setVolume(bean.getVolume());
                //巡检单位
                task.setRouterid(bean.getRouterid());
                task.setRoutername(bean.getRoutername());
                //查询巡检人员
                EntityWrapper<Cunsumer> cunsumerEntityWrapper = new EntityWrapper<>();
                cunsumerEntityWrapper.eq("routerid",bean.getRouterid());
                cunsumerEntityWrapper.eq("leader",1);
                List<Cunsumer> listc = cunsumerMapper.selectList(cunsumerEntityWrapper);
                Cunsumer cunsumer = listc.get(0);
                task.setCunsumerid(cunsumer.getId());
                task.setCunsumername(cunsumer.getName());
                task.setCunsumermobile(cunsumer.getMobile());

                task.setFactoryname(bean.getFactoryname());
                task.setFactoryphone(bean.getFactoryphone());
                task.setFactoryuser(bean.getFactoryuser());

                task.setUsertype("-");
                //暂不启用
                task.setStatus(0);
                task.setTaskdate(DateUtil.format(starttime,"yyyyMM"));
                try{
                    normalMapper.insert(task);
                }catch (Exception e){
                    //System.out.println("插入失败："+task);
                }

            }else{
            }
        }
    }

    @Override
    public void updateStatus() {
        //获取7天后的日期
        String date = DateUtil.getDateLast(7);
        EntityWrapper<Normal> wrapper = new EntityWrapper<>();
        wrapper.lt("createtime",date);
        wrapper.eq("status",0);
        List<Normal> list = normalMapper.selectList(wrapper);
        Normal bean = new Normal();
        bean.setStatus(10);
        normalMapper.update(bean,wrapper);
        //把计划插入到任务中
        for(Normal normal: list){
            Task task = new Task();
            BeanUtils.copyProperties(normal,task);
            //用于统计的时间
            task.setStarttime(normal.getCreatetime());
            task.setCid(task.getCunsumerid());
            task.setCname(task.getCunsumername());
            task.setCmobile(task.getCunsumermobile());
            //任务类型名称
            Param p = getParam(task.getTasktype());
            task.setTasktypestr(p.getTitle());
            task.setStatus(10);
            //添加任务所属的日期
            task.setTaskdate(DateUtil.format(task.getCreatetime(),"yyyyMM"));
            taskMapper.insert(task);
        }
    }

    private List<TaskType> getListDate(Date start, Date end,String type){
        List<TaskType> listDate = new ArrayList<>();
        String rr = DateUtil.format(start,"dd");

        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(new Date());

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
        while (tempStart.before(tempEnd)) {
            //处理2月没有30号的问题
            if(DateUtil.format(tempStart.getTime(),"MM").equals("02")) {
                if(rr.equals("29")||rr.equals("30")||rr.equals("31")) {
                    if("28".equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }else{
                    if (DateUtil.format(start, "dd").equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }
                //处理月大月小的问题
            }else if(DateUtil.format(tempStart.getTime(),"MM").equals("04")||
                    DateUtil.format(tempStart.getTime(),"MM").equals("06")||
                    DateUtil.format(tempStart.getTime(),"MM").equals("09")||
                    DateUtil.format(tempStart.getTime(),"MM").equals("11")) {
                if(rr.equals("31")) {
                    if("30".equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }else{
                    if (DateUtil.format(start, "dd").equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }

            }else{
                if (DateUtil.format(start, "dd").equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                    listDate.add(new TaskType(tempStart.getTime(),type));
                }
            }
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return listDate;
    }

    public static void main(String[] args){
        Date start = DateUtil.toDate("2019-05-01");
        Date end = DateUtil.toDate("2021-05-13");
        NormalServiceImpl normalService = new NormalServiceImpl();
        List<TaskType> list = normalService.getListDate(start,end,"50");
        for(TaskType d:list){
            System.out.println(d);
        }

//        NormalServiceImpl normalService = new NormalServiceImpl();
//        normalService.createTask();
        //4008881551
    }
    /**
     * 运维类型查询
     * @param tasktype
     * @return
     */
    private Param getParam(Integer tasktype){
        EntityWrapper<Param> query = new EntityWrapper<>();
        query.eq("groups","运维类型");
        query.eq("value",tasktype);
        Param p = paramService.selectOne(query);
        return p;
    }

}

class TaskType{
    private Date time;
    private String type;

    public TaskType(Date time, String type) {
        this.time = time;
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return "TaskType{" +
                "time=" + DateUtil.format(time) +
                ", type='" + type + '\'' +
                '}';
    }
}
